package com.webserver.core;

import jdk.internal.org.objectweb.asm.Handle;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程任务负责与指定的客户端完成HTTP交互
 * 每次http交互都采取一问一答得规则，因此交互由三步来完成：
 * 1.解析请求
 * 2.处理请求
 * 3.发送相应
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {

            //1.解析请求
            //1.1解析请求行
            String line = readLine();
            System.out.println(line);
            //请求行的相关信息
            String method;//请求方式
            String uri;//抽象路径
            String protocol;//协议

            String[] m =  line.split(" ");
            method = m[0];
            uri = m[1];
            protocol = m[2];

//            line.substring(1,2);
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protoval:"+protocol);

            //1.2解析消息头
            //消息头相关信息
            Map<String,String> headers = new HashMap<>();


            while (true){
                line =  readLine();
                if (line.isEmpty()) {
                    break;
                }
                String[] str = line.split(": ");
                headers.put(str[0],str[1]);
//                System.out.println("消息头："+line);
            }
            System.out.println("headers:"+headers);

//            while (line.length() != 0){
//                line = readLine();
//                System.out.println(line);
//            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char pre = ' ',cur = ' ';//pre上次读的字符，cur本次读的字符
        int d ;
        while((d = in.read())!=-1){
            cur = (char) d;
            if (pre ==13&& cur==10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }
}
